import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { get, post } from "../../utils/request";
import { useUserStore } from "./useUserStore";


export const useBindingStore = defineStore("binding", () => {
  
  const userStore = useUserStore();
  
  // 初始化绑定列表为空数组
  const bindingList = ref([]);
  
  // 当前选中的绑定ID
  const curBindingId = ref(null);
  
  // 获取当前选中的绑定ID
  const getCurBindingId = computed(() => curBindingId.value);
  
  // 设置当前选中的绑定ID
  const setCurBindingId = (id) => {
    if (id) {
      curBindingId.value = id;
    }
  };

  // 获取绑定列表，确保返回数组
  const getBindingList = computed(() => {
    return bindingList.value || [];
  });
  
  // 获取绑定列表数据
  const fetchBindingList = async () => {
    try {
      const res = await get(
        `/users/${userStore.getUserData.id}/bindingList`,
        "api/v1"
      );
      if (res?.code === 200) {
        bindingList.value = res.data || [];
        // 如果当前没有选中的绑定ID，且有绑定列表，则选中第一个
        if (!curBindingId.value && bindingList.value.length > 0) {
          curBindingId.value = bindingList.value[0].id;
        }
      } else {
        console.error('获取绑定列表失败:', res.message);
        bindingList.value = [];
      }
    } catch (error) {
      console.error('获取绑定列表出错:', error);
      bindingList.value = [];
    }
  };

  const addBinding = async (data) => {
    bindingList.value.push(data);
    await post("/users/binding", data, "api/v1");
  };

  const deleteBinding = async (id) => {
    try {
      const index = bindingList.value.findIndex((item) => item.id == id);

      if (index !== -1) {
        const bind = bindingList.value[index];
        const data = { userId: bind.binderId, bindedUserId: bind.bindedId };
        bindingList.value.splice(index, 1);
        await post("/users/unbinding", data, "api/v1");
      }

    } catch (error) {
        console.error("Error deleting binding:", error);
    }
  };

  return {
    bindingList,
    fetchBindingList,
    addBinding,
    deleteBinding,
    getBindingList,

    
    getCurBindingId,
    setCurBindingId

  };
});

